#include "lfhfplot.h"

LFHFPlot::LFHFPlot() {}
void LFHFPlot::drawMultiCurves(QChartView* chartView,
                                        QString titleName,
                                        QVector<QString>lineName,
                                        bool isRatio,
                                        const QVector<QVector<double>>& xDataList,
                                        const QVector<QVector<double>>& yDataList)
{
    // 定义曲线样式
    const QList<QColor> colors = {QColor(127, 127, 255, 255),QColor(179, 127, 255, 255),QColor(127, 255, 255, 255)};

    QChart* chart = new QChart();
    chart->setBackgroundBrush(Qt::transparent);
    chart->setMargins(QMargins(0, 0, 0, 0));
    chart->setTitle(titleName);
    chart->setAnimationOptions(QChart::SeriesAnimations);
    chart->legend()->setAlignment(Qt::AlignTop);
    // 创建曲线
    double minv=yDataList[0][0];
    double maxv=yDataList[0][0];
    int lineNums=xDataList.size();
    for(int i=0;i<lineNums;i++)
    {
        QLineSeries* series = new QLineSeries();
        series->setName(lineName.at(i));
        series->setColor(colors[i]);
        int len=xDataList[i].size();
        for (int j = 0; j < len; ++j) {
            series->append(xDataList[i][j], yDataList[i][j]);
            if(yDataList[i][j]>maxv)
                maxv=yDataList[i][j];
            if(yDataList[i][j]<minv)
                minv=yDataList[i][j];
        }
        chart->addSeries(series);
    }

    // 坐标轴配置
    QValueAxis* axisX = new QValueAxis();
    axisX->setRange(0, xDataList[0].last());  // 设置X轴范围
    axisX->setTitleText("Time (S)");
    axisX->setGridLineVisible(false);

    QValueAxis* axisY = new QValueAxis();
    if(isRatio)
        axisY->setTitleText("LF/HF (ratio)");
    else
        axisY->setTitleText("Power (ms^2)");
    axisY->setGridLineColor(QColor(200, 200, 200, 100));
    axisY->setRange(0,maxv);
    axisY->setLabelsFont(QFont("微软雅黑", 8));

    chart->addAxis(axisX, Qt::AlignBottom);
    chart->addAxis(axisY, Qt::AlignLeft);
    // chart->legend()->show();
    chart->legend()->setVisible(true);

    // 关联所有系列到坐标轴
    for (auto series : chart->series()) {
        series->attachAxis(axisX);
        series->attachAxis(axisY);
    }

    chartView->setChart(chart);
    chartView->setRenderHint(QPainter::Antialiasing);
}
